﻿using System;
using System.Globalization;
using System.Reflection;
using Microsoft.Practices.Unity.InterceptionExtension;
using VerifyArgs;
using EP.Caching.Attributes;

namespace EP.Caching.Attributes {
	[Serializable]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
	public class InvalidateCacheTriggerAttribute : Attribute {
		private readonly string _validateMethod;
		public string ValidateMethod { get { return _validateMethod; } }

		public InvalidateCacheTriggerAttribute(string validateMethod) {
			Verify.Args(new { validateMethod }).NotNullOrEmpty();

			_validateMethod = validateMethod;
		}

		public int Order { get; set; }

		public bool IsValid(MethodBase input, object target) {
			Verify.Args(new { input, input.DeclaringType, target }).NotNull();

			var retVal = false;

			var valMethod = input.DeclaringType.GetMethod(_validateMethod, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
			if (valMethod != null)
				retVal = Convert.ToBoolean(valMethod.Invoke(target, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static, null, new object[] { input }, CultureInfo.CurrentCulture));

			return retVal;
		}
	}
}
